package structuralPattern.decorator.example02;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * 具体装饰者类
 * 对文件内容加解密
 */
public class EncryptionDataDecorator extends DataLoaderDecorator{

    public EncryptionDataDecorator(DataLoder dataLoder) {
        super(dataLoder);
    }

    @Override
    public String read() {
        return decode(super.read());
    }

    @Override
    public void write(String str) {
        String encode = encode(str);
        super.write(encode);
    }

    // 扩展写加密
    private String encode(String data){
        try {
            byte[] bytes = data.getBytes("utf-8");
            Base64.Encoder encoder = Base64.getEncoder();
            String result = encoder.encodeToString(bytes);
            return result;
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    // 扩展读解密
    private String decode(String data){
        try {
            Base64.Decoder decoder = Base64.getDecoder();
            String result = new String(decoder.decode(data), "utf-8");
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
